package cn.tedu.straw.redis.tag.schedule;

import cn.tedu.straw.commons.vo.TagVO;
import cn.tedu.straw.redis.tag.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class TagSchedule {

    @Autowired
    ITagService tagService;
    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void writeTags2Redis() {
        // 从数据库中读取标签列表
        List<TagVO> tags = tagService.getTagList();
        // 标签列表数据在Redis中的Key
        String tagsKey = "tags";
        // 删除原有的标签列表
        redisTemplate.delete(tagsKey);
        // 通过RedisTemplate获取列表类型的“操作器”
        ListOperations<String, Serializable> ops = redisTemplate.opsForList();
        //获取普通类型的操作器
        ValueOperations<String,Serializable> valueOps=redisTemplate.opsForValue();
        // 向Redis中写入标签列表
        for (TagVO tag : tags) {
            ops.rightPush(tagsKey, tag);
            valueOps.set("tag"+tag.getId(),tag);
        }
    }

}




